package com.elepro.shoppingmall.config.security.handler;

import com.elepro.shoppingmall.entity.User;
import com.google.gson.Gson;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Data
public class ResultMsg {
    int code;
    String message;
    User user;

    //无权访问
    public static ResultMsg denyAccess(String message) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setCode(300);
        resultMsg.setMessage(message);
        return resultMsg;
    }

    //登录成功
    public static ResultMsg success(String message, User user) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setCode(200);
        resultMsg.setMessage(message);
        resultMsg.setUser(user);
        return resultMsg;
    }

    //登录失败
    public static ResultMsg fail(String message) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setCode(400);
        resultMsg.setMessage(message);
        return resultMsg;
    }

    //未认证
    public static ResultMsg unauthorized(String message) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setCode(401);
        resultMsg.setMessage(message);
        return resultMsg;
    }

    //权限不足
    public static ResultMsg canNotAccess(String message) {
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setCode(300);
        resultMsg.setMessage(message);
        return resultMsg;
    }

    //返回响应
    public static void returnResponse(ResultMsg resultMsg, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        String jsonData = new Gson().toJson(resultMsg);
        System.out.println(jsonData);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(jsonData);
        writer.flush();
        writer.close();
    }
}
